<%@ page language="java" pageEncoding="UTF-8" %>
<%@ page import="com.alibaba.fastjson.JSONArray" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="okhttp3.*" %>
<%@ page import="weaver.common.DateUtil" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.formmode.setup.ModeRightInfo" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.TimeUtil" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="java.util.*" %>
<%@ page import="java.util.concurrent.TimeUnit" %>
<%--获取流水号--%>
<%
    RecordSet rs = new RecordSet();
    RecordSet rs1 = new RecordSet();
    try {
        String curdate = DateUtil.getFullDate();
        int pageSize = 2000;
        out.print(">>>>>WeaSyncKingdeeBaseInfoCronJob>>>>>curdate=" + curdate + "<br/>");
        //查询接口状态为启用的接口
        rs.executeQuery("select * from uf_jdbwpzb where jkzt=0 and ywlx=1");
        out.print(">>>>>WeaSyncKingdeeBaseInfoCronJob>>>>>接口数量=" + rs.getCounts() + "<br/>");
        while (rs.next()) {
            String mainid = Util.null2String(rs.getString("id"));//id
            String jkbm = Util.null2String(rs.getString("jkbm"));//接口编码
            String qqdz = Util.null2String(rs.getString("qqdz"));//请求地址
            String dybd = Util.null2String(rs.getString("dybd"));//对应表单
            String qqfs = Util.null2String(rs.getString("qqfs"));//请求方式
            JSONObject dataParamJson = new JSONObject();
            Map<String, String> fieldMap = new HashMap<>();
            rs1.executeQuery("select * from uf_jdbwpzb_dt1 where mainid=?", mainid);
            while (rs1.next()) {
                String qqcsj = Util.null2String(rs1.getString("qqcsj"));
                String qqcsz = Util.null2String(rs1.getString("qqcsz"));
                dataParamJson.put(qqcsj, qqcsz);
            }
            out.print(">>>>>" + jkbm + ">>>>>dataParamJson=" + dataParamJson + "<br/>");
            rs1.executeQuery("select * from uf_jdbwpzb_dt2 where mainid=?", mainid);
            while (rs1.next()) {
                String oazd = Util.null2String(rs1.getString("oazd"));
                String jdzd = Util.null2String(rs1.getString("jdzd"));
                fieldMap.put(oazd, jdzd);
            }
            out.print(">>>>>" + jkbm + ">>>>>fieldMap=" + fieldMap + "<br/>");
            if ("0".equals(qqfs)) {//GET请求
                int totalCount = 0;
                if (totalCount == 0) {//默认查询第一页的数据
                    out.print(">>>>>" + jkbm + ">>>>>查询第1页的数据<br/>");
                    String paramStr = "pageSize=" + pageSize + "&pageNo=1";
                    if (!dataParamJson.isEmpty()) {
                        for (Object key : dataParamJson.keySet()) {
                            Object value = Util.null2String(dataParamJson.get(key));
                            paramStr += "&" + key + "=" + value;
                        }
                    }
                    out.print(">>>>>" + jkbm + ">>>>>paramStr=" + paramStr + "<br/>");
                    JSONObject resultJson = sendOKHttpGetRequest(qqdz + "?" + paramStr);
                    String message = Util.null2String(resultJson.getString("message"));
                    if ("success".equals(message)) {
                        String datas = Util.null2String(resultJson.getString("datas"));
                        JSONObject datasJson = JSONObject.parseObject(datas);
                        String errorCode = datasJson.getString("errorCode");
                        if ("0".equals(errorCode)) {
                            JSONObject dataJson = datasJson.getJSONObject("data");
                            JSONArray rowsList = dataJson.getJSONArray("rows");
                            totalCount = dataJson.getIntValue("totalCount");
                            int insertCount = 0;
                            int updateCount = 0;
                            String dataResult = isExistData("wyid", dybd);
                            List<String> dataList = Arrays.asList(dataResult.split(","));
                            for (int i = 0; i < rowsList.size(); i++) {
                                Map<String, Object> map = new HashMap<>();
                                JSONObject rowJson = rowsList.getJSONObject(i);
                                String id = Util.null2String(rowJson.getString("id"));
                                if (!dataList.contains(id)) {
                                    map.put("wyid", id);
                                    map.put("rqsj", curdate);
                                    for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                                        String oazd = entry.getKey();
                                        String jdzd = entry.getValue();
                                        map.put(oazd, Util.null2String(rowJson.getString(jdzd)));
                                    }
                                    if (insertModelData(dybd, map)) {
                                        insertCount++;
                                    }
                                } else {
                                    for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                                        String oazd = entry.getKey();
                                        String jdzd = entry.getValue();
                                        map.put(oazd, Util.null2String(rowJson.getString(jdzd)));
                                    }
                                    if (updateModelData(dybd, id, map)) {
                                        updateCount++;
                                    }

                                }
                            }
                            out.print(">>>>>" + jkbm + ">>>>>总数量：[" + totalCount + "]<br/>");
                            out.print(">>>>>" + jkbm + ">>>>>插入数量：[" + insertCount + "]<br/>");
                            out.print(">>>>>" + jkbm + ">>>>>更新数量：[" + updateCount + "]<br/>");
                        } else {
                            out.print(">>>>>" + jkbm + ">>>>>接口异常返回：" + datas + "<br/>");
                        }
                    }
                }

                if (totalCount > pageSize) {//默认查询后几页的数据
                    int count = (int) Math.ceil(totalCount / pageSize);
                    for (int i = 1; i <= count; i++) {
                        out.print(">>>>>" + jkbm + ">>>>>查询第" + (i + 1) + "页的数据<br/>");
                        String paramStr = "pageSize=" + pageSize + "&pageNo=" + (i + 1);
                        for (Object key : dataParamJson.keySet()) {
                            Object value = Util.null2String(dataParamJson.get(key));
                            paramStr += "&" + key + "=" + value;
                        }
                        out.print(">>>>>" + jkbm + ">>>>>paramStr=" + paramStr + "<br/>");
                        JSONObject resultJson = sendOKHttpGetRequest(qqdz + "?" + paramStr);
                        String message = Util.null2String(resultJson.getString("message"));
                        if ("success".equals(message)) {
                            String datas = Util.null2String(resultJson.getString("datas"));
                            JSONObject datasJson = JSONObject.parseObject(datas);
                            String errorCode = datasJson.getString("errorCode");
                            if ("0".equals(errorCode)) {
                                JSONObject dataJson = datasJson.getJSONObject("data");
                                JSONArray rowsList = dataJson.getJSONArray("rows");
                                int insertCount = 0;
                                int updateCount = 0;
                                String dataResult = isExistData("wyid", dybd);
                                List<String> dataList = Arrays.asList(dataResult.split(","));
                                for (int j = 0; j < rowsList.size(); j++) {
                                    Map<String, Object> map = new HashMap<>();
                                    JSONObject rowJson = rowsList.getJSONObject(j);
                                    String id = Util.null2String(rowJson.getString("id"));
                                    if (!dataList.contains(id)) {
                                        map.put("wyid", id);
                                        map.put("rqsj", curdate);
                                        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                                            String oazd = entry.getKey();
                                            String jdzd = entry.getValue();
                                            map.put(oazd, Util.null2String(rowJson.getString(jdzd)));
                                        }
                                        if (insertModelData(dybd, map)) {
                                            insertCount++;
                                        }
                                    } else {
                                        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                                            String oazd = entry.getKey();
                                            String jdzd = entry.getValue();
                                            map.put(oazd, Util.null2String(rowJson.getString(jdzd)));
                                        }
                                        if (updateModelData(dybd, id, map)) {
                                            updateCount++;
                                        }

                                    }
                                }
                                out.print(">>>>>" + jkbm + ">>>>>总数量：[" + totalCount + "]<br/>");
                                out.print(">>>>>" + jkbm + ">>>>>插入数量：[" + insertCount + "]<br/>");
                                out.print(">>>>>" + jkbm + ">>>>>更新数量：[" + updateCount + "]<br/>");
                            } else {
                                out.print(">>>>>" + jkbm + ">>>>>接口异常返回：" + datas + "<br/>");
                            }
                        }
                    }
                }
            } else {//POST请求
                int totalCount = 0;
                if (totalCount == 0) {
                    out.print(">>>>>" + jkbm + ">>>>>查询第1页的数据<br/>");
                    JSONObject paramJson = new JSONObject();
                    paramJson.put("data", dataParamJson);
                    paramJson.put("pageSize", pageSize);
                    paramJson.put("pageNo", 1);
                    out.print(">>>>>" + jkbm + ">>>>>paramJson=" + paramJson + "<br/>");
                    JSONObject resultJson = sendOKHttpPostRequest(qqdz, paramJson.toJSONString());
                    String message = Util.null2String(resultJson.getString("message"));
                    if ("success".equals(message)) {
                        String datas = Util.null2String(resultJson.getString("datas"));
                        JSONObject datasJson = JSONObject.parseObject(datas);
                        String errorCode = datasJson.getString("errorCode");
                        if ("0".equals(errorCode)) {
                            JSONObject dataJson = datasJson.getJSONObject("data");
                            totalCount = dataJson.getIntValue("totalCount");
                            JSONArray rowsList = dataJson.getJSONArray("rows");
                            int insertCount = 0;
                            int updateCount = 0;
                            String dataResult = isExistData("wyid", dybd);
                            List<String> dataList = Arrays.asList(dataResult.split(","));
                            for (int i = 0; i < rowsList.size(); i++) {
                                Map<String, Object> map = new HashMap<>();
                                JSONObject rowJson = rowsList.getJSONObject(i);
                                String id = Util.null2String(rowJson.getString("id"));
                                if (!dataList.contains(id)) {
                                    map.put("wyid", id);
                                    map.put("rqsj", curdate);
                                    for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                                        String oazd = entry.getKey();
                                        String jdzd = entry.getValue();
                                        map.put(oazd, Util.null2String(rowJson.getString(jdzd)));
                                    }
                                    if (insertModelData(dybd, map)) {
                                        insertCount++;
                                    }
                                } else {
                                    for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                                        String oazd = entry.getKey();
                                        String jdzd = entry.getValue();
                                        map.put(oazd, Util.null2String(rowJson.getString(jdzd)));
                                    }
                                    if (updateModelData(dybd, id, map)) {
                                        updateCount++;
                                    }
                                }
                            }
                            out.print(">>>>>" + jkbm + ">>>>>总数量：[" + totalCount + "]<br/>");
                            out.print(">>>>>" + jkbm + ">>>>>插入数量：[" + insertCount + "]<br/>");
                            out.print(">>>>>" + jkbm + ">>>>>更新数量：[" + updateCount + "]<br/>");
                        } else {
                            out.print(">>>>>" + jkbm + ">>>>>接口异常返回：" + datas + "<br/>");
                        }
                    }
                }
                if (totalCount > pageSize) {//默认查询后几页的数据
                    int count = (int) Math.ceil(totalCount / pageSize);
                    for (int i = 0; i <= count; i++) {
                        out.print(">>>>>" + jkbm + ">>>>>查询第" + (i + 2) + "页的数据<br/>");
                        JSONObject paramJson = new JSONObject();
                        paramJson.put("data", dataParamJson);
                        paramJson.put("pageSize", pageSize);
                        paramJson.put("pageNo", i + 2);
                        out.print(">>>>>" + jkbm + ">>>>>paramJson=" + paramJson + "<br/>");
                        JSONObject resultJson = sendOKHttpPostRequest(qqdz, paramJson.toJSONString());
                        String message = Util.null2String(resultJson.getString("message"));
                        if ("success".equals(message)) {
                            String datas = Util.null2String(resultJson.getString("datas"));
                            JSONObject datasJson = JSONObject.parseObject(datas);
                            String errorCode = datasJson.getString("errorCode");
                            if ("0".equals(errorCode)) {
                                JSONObject dataJson = datasJson.getJSONObject("data");
                                JSONArray rowsList = dataJson.getJSONArray("rows");
                                int insertCount = 0;
                                int updateCount = 0;
                                String dataResult = isExistData("wyid", dybd);
                                List<String> dataList = Arrays.asList(dataResult.split(","));
                                for (int j = 0; j < rowsList.size(); j++) {
                                    Map<String, Object> map = new HashMap<>();
                                    JSONObject rowJson = rowsList.getJSONObject(j);
                                    String id = Util.null2String(rowJson.getString("id"));
                                    if (!dataList.contains(id)) {
                                        map.put("wyid", id);
                                        map.put("rqsj", curdate);
                                        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                                            String oazd = entry.getKey();
                                            String jdzd = entry.getValue();
                                            map.put(oazd, Util.null2String(rowJson.getString(jdzd)));
                                        }
                                        if (insertModelData(dybd, map)) {
                                            insertCount++;
                                        }
                                    } else {
                                        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                                            String oazd = entry.getKey();
                                            String jdzd = entry.getValue();
                                            map.put(oazd, Util.null2String(rowJson.getString(jdzd)));
                                        }
                                        if (updateModelData(dybd, id, map)) {
                                            updateCount++;
                                        }
                                    }
                                }
                                out.print(">>>>>" + jkbm + ">>>>>总数量：[" + totalCount + "]<br/>");
                                out.print(">>>>>" + jkbm + ">>>>>插入数量：[" + insertCount + "]<br/>");
                                out.print(">>>>>" + jkbm + ">>>>>更新数量：[" + updateCount + "]<br/>");
                            } else {
                                out.print(">>>>>" + jkbm + ">>>>>接口异常返回：" + datas + "<br/>");
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        out.print("WeaSyncKingdeeBaseInfoCronJob" + e);
        e.printStackTrace();
    }
%>
<%!
    private final BaseBean baseBean = new BaseBean();
    private static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
    private static final int CONNECT_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private static final int READ_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    private static final int WRITE_TIMEOUT_MILLIS = 60 * 1000; // 60秒
    // 定义常量
    private static final String RES_CODE_ZERO = "0";
    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
            .readTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
            .writeTimeout(WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
            .build();

    /**
     * 获取token
     *
     * @return
     */
    private String getToken() {
        String token = "";
        JSONObject returnJson = getTokenBaseInfo();
        String apiUrl = returnJson.getString("apiUrl");
        JSONObject paramJson = returnJson.getJSONObject("paramJson");
        paramJson.put("nonce", UUID.randomUUID().toString());
        paramJson.put("timestamp", DateUtil.getFullDate());
        try {
            RequestBody body = RequestBody.create(mediaType, paramJson.toJSONString());
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (response.isSuccessful()) {
                if (!result.isEmpty()) {
                    JSONObject resultJsonObj = JSONObject.parseObject(result);
                    String errorCode = resultJsonObj.getString("errorCode");
                    if (RES_CODE_ZERO.equals(errorCode)) {
                        token = resultJsonObj.getJSONObject("data").getString("access_token");
                    }
                }
            }
        } catch (Exception e) {
            baseBean.writeLog(">>>>>sendOKHttpPostRequest>>>>>Exception e:", e);
        }
        return token;
    }

    /**
     * get请求
     *
     * @param apiUrl
     * @return
     */
    public JSONObject sendOKHttpGetRequest(String apiUrl) {
        String accesstoken = getToken();
        JSONObject resultJson = new JSONObject();
        String responseMsg = "";
        try {
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .get()
                    .addHeader("accesstoken", accesstoken)
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (!response.isSuccessful()) {
                responseMsg = "response code :" + response.code();
            } else {
                if (!result.isEmpty()) {
                    resultJson.put("datas", result);
                    responseMsg = "success";
                } else {
                    responseMsg = "response result is null";
                }
            }
        } catch (Exception e) {
            responseMsg = "response timeout or network error";
            baseBean.writeLog(">>>>>sendOKHttpGetRequest>>>>>Exception e:", e);
        }

        resultJson.put("message", responseMsg);
        return resultJson;
    }

    /**
     * Post请求
     *
     * @param params
     * @param apiUrl
     * @return
     */
    public JSONObject sendOKHttpPostRequest(String apiUrl, String params) {
        String accesstoken = getToken();
        JSONObject resultJson = new JSONObject();
        String responseMsg = "";
        try {
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("accesstoken", accesstoken)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            response.body().close(); // 保证资源被释放
            // 增加对HTTP状态码的检查
            if (!response.isSuccessful()) {
                responseMsg = "response code :" + response.code();
            } else {
                if (!result.isEmpty()) {
                    resultJson.put("datas", result);
                    responseMsg = "success";
                } else {
                    responseMsg = "response result is null";
                }
            }
        } catch (Exception e) {
            responseMsg = "response timeout or network error";
            baseBean.writeLog(">>>>>sendOKHttpPostRequest>>>>>Exception e:", e);
        }
        resultJson.put("message", responseMsg);
        return resultJson;
    }


    private JSONObject getTokenBaseInfo() {
        RecordSet rs = new RecordSet();
        JSONObject returnJson = new JSONObject();
        JSONObject paramJson = new JSONObject();
        rs.executeQuery("select * from uf_jdbwpzb where jkbm='getToken'");
        rs.next();
        String mainid = Util.null2String(rs.getString("id"));
        String apiUrl = Util.null2String(rs.getString("qqdz"));
        rs.executeQuery("select * from uf_jdbwpzb_dt1 where mainid=?", mainid);
        while (rs.next()) {
            String qqcsj = Util.null2String(rs.getString("qqcsj"));
            String qqcsz = Util.null2String(rs.getString("qqcsz"));
            paramJson.put(qqcsj, qqcsz);
        }
        returnJson.put("apiUrl", apiUrl);
        returnJson.put("paramJson", paramJson);
        return returnJson;
    }

    /**
     * 建模权限重构
     *
     * @param userid
     * @param formmodeid
     * @param id
     */
    private void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    /**
     * 将数据插入表单建模
     *
     * @param map
     */
    public boolean insertModelData(String tablename, Map<String, Object> map) {
        int dataid = 0;
        int userid = 1;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        BaseBean baseBean = new BaseBean();
        boolean result = false;
        //查询该模块表名
        try {
            rs.executeQuery("select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename='" + tablename + "'");
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values" +
                    "('" + uuid + "','" + userid + "','" + TimeUtil.getCurrentDateString() + "','" + TimeUtil.getOnlyCurrentTimeString() + "','" + modeid + "')";
            if (rs.executeUpdate(insSql)) {
                rs1.executeQuery("select id from " + tablename + " where modeuuid='" + uuid + "'");
                rs1.next();
                dataid = Util.getIntValue(rs1.getString("id"));
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        updatesql += key + "='" + map.get(key).toString() + "',";
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        baseBean.writeLog(">>>>>insertModelData>>>>updatesql=" + updatesql);
                        if (!rs.executeUpdate(updatesql)) {
                            rs1.executeUpdate("delete from " + tablename + " where id=?", dataid);
                        } else {
                            result = true;
                        }
                    }
                    //进行权限重构
                    newModeRight(userid, modeid, dataid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新数据
     *
     * @param tablename 表名
     * @param map 数据集合
     * @param dataid 更新用唯一标识
     * @return
     */
    public boolean updateModelData(String tablename, String dataid, Map<String, Object> map) {
        RecordSet rs = new RecordSet();
        BaseBean baseBean = new BaseBean();
        String updatesql = "update " + tablename + " set  ";
        String valuesStr = "";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (valuesStr.equals("")) {
                valuesStr = key + "='" + map.get(key) + "'";
            } else {
                valuesStr += "," + key + "='" + map.get(key) + "'";
            }
        }
        updatesql += valuesStr + " where wyid='" + dataid + "'";
        baseBean.writeLog(">>>>>updateModelData>>>>updatesql=" + updatesql);
        return rs.execute(updatesql);
    }

    /**
     * 判断数据是否存在
     *
     * @param fileName
     * @param tableName
     * @return
     */
    public String isExistData(String fileName, String tableName) {
        StringBuilder sb = new StringBuilder();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select " + fileName + " from " + tableName);
        while (rs.next()) {
            String value = Util.null2String(rs.getString(1));
            sb.append(value).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

%>